package com.example.javaproject.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.javaproject.common.R;
import com.example.javaproject.entity.Salary;
import com.example.javaproject.service.SalaryService;
import com.example.javaproject.dto.SalaryDTO;
import com.example.javaproject.dto.SalaryStatsDTO;
import com.example.javaproject.service.StudentService;
import com.example.javaproject.service.TeacherService;
import com.example.javaproject.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/salary")
public class SalaryController {

    @Autowired
    private SalaryService salaryService;

    @Autowired
    private StudentService studentService;
    
    @Autowired
    private TeacherService teacherService;

    @GetMapping("/stats")
    public R getStats() {
        List<SalaryStatsDTO> stats = salaryService.getSalaryStats();
        return R.ok(stats);
    }

    @GetMapping("/list")
    public R list(@RequestParam(defaultValue = "1") Integer page,
                  @RequestParam(defaultValue = "10") Integer size,
                  @RequestParam(required = false) Integer status,
                  @RequestParam(required = false) String studentName,
                  @RequestParam(required = false) String teacherName,
                  @RequestParam(required = false) String positionName) {

        Page<SalaryDTO> pageObj = salaryService.getSalaryPage(
                new Page<>(page, size), status, studentName, teacherName, positionName
        );
        return R.ok(pageObj);
    }

    @GetMapping("/teacher/list")
    public R teacherSalaryList(@RequestHeader("Authorization") String authHeader,
                               @RequestParam(defaultValue = "1") Integer page,
                               @RequestParam(defaultValue = "10") Integer size,
                               @RequestParam(required = false) String positionName,
                               @RequestParam(required = false) String studentName,
                               @RequestParam(required = false) Integer status) {
        if (authHeader == null || authHeader.isEmpty()) {
            return R.error("未登录");
        }
        String token = authHeader.startsWith("Bearer ") ? authHeader.substring(7) : authHeader;
        Integer userId;
        try {
            userId = (Integer) JwtUtil.parseToken(token).get("userId");
        } catch (Exception e) {
            return R.error("token无效");
        }
        
        var teacher = teacherService.getByUserId(userId);
        if (teacher == null) {
            return R.error("教师信息不存在");
        }
        Integer teacherId = teacher.getId();
        
        Page<SalaryDTO> pageObj = salaryService.getTeacherSalaryPage(
                new Page<>(page, size), teacherId, status, studentName, positionName
        );
        return R.ok(pageObj);
    }

    
    @PostMapping("/teacher/approve")
    public R teacherApprove(@RequestHeader("Authorization") String authHeader,
                           @RequestBody SalaryDTO salaryDTO) {
        if (authHeader == null || authHeader.isEmpty()) {
            return R.error("未登录");
        }
        String token = authHeader.startsWith("Bearer ") ? authHeader.substring(7) : authHeader;
        Integer userId;
        try {
            userId = (Integer) JwtUtil.parseToken(token).get("userId");
        } catch (Exception e) {
            return R.error("token无效");
        }
        
        var teacher = teacherService.getByUserId(userId);
        if (teacher == null) {
            return R.error("教师信息不存在");
        }
        
        boolean success = salaryService.teacherApproveSalary(salaryDTO.getId(), teacher.getId());
        return success ? R.ok(null) : R.error("審核失敗");
    }

    
    @PostMapping("/teacher/reject")
    public R teacherReject(@RequestHeader("Authorization") String authHeader,
                          @RequestBody SalaryDTO salaryDTO) {
        if (authHeader == null || authHeader.isEmpty()) {
            return R.error("未登录");
        }
        String token = authHeader.startsWith("Bearer ") ? authHeader.substring(7) : authHeader;
        Integer userId;
        try {
            userId = (Integer) JwtUtil.parseToken(token).get("userId");
        } catch (Exception e) {
            return R.error("token无效");
        }
        
       
        var teacher = teacherService.getByUserId(userId);
        if (teacher == null) {
            return R.error("教师信息不存在");
        }
        
        boolean success = salaryService.teacherRejectSalary(salaryDTO.getId(), teacher.getId());
            return success ? R.ok(null) : R.error("拒绝失败");
    }

   
    @PostMapping("/teacher/resend")
    public R teacherResend(@RequestHeader("Authorization") String authHeader,
                          @RequestBody SalaryDTO salaryDTO) {
        if (authHeader == null || authHeader.isEmpty()) {
            return R.error("未登录");
        }
        String token = authHeader.startsWith("Bearer ") ? authHeader.substring(7) : authHeader;
        Integer userId;
        try {
            userId = (Integer) JwtUtil.parseToken(token).get("userId");
        } catch (Exception e) {
            return R.error("token无效");
        }
       
        var teacher = teacherService.getByUserId(userId);
        if (teacher == null) {
            return R.error("教师信息不存在");
        }
        boolean success = salaryService.teacherResendSalary(salaryDTO.getId(), teacher.getId());
        return success ? R.ok(null) : R.error("操作失败");
    }

    // 新增：教师修改工资信息
    @PostMapping("/teacher/update")
    public R teacherUpdateSalary(@RequestHeader("Authorization") String authHeader,
                                @RequestBody SalaryDTO salaryDTO) {
        if (authHeader == null || authHeader.isEmpty()) {
            return R.error("未登录");
        }
        String token = authHeader.startsWith("Bearer ") ? authHeader.substring(7) : authHeader;
        Integer userId;
        try {
            userId = (Integer) JwtUtil.parseToken(token).get("userId");
        } catch (Exception e) {
            return R.error("token无效");
        }
       
        var teacher = teacherService.getByUserId(userId);
        if (teacher == null) {
            return R.error("教师信息不存在");
        }
        
        boolean success = salaryService.teacherUpdateSalary(salaryDTO.getId(), teacher.getId(), 
                                                          salaryDTO.getTotalHour(), salaryDTO.getTotalSalary());
        return success ? R.ok(null) : R.error("修改失败");
    }

    
    @GetMapping("/test")
    public R test() {
        QueryWrapper<Salary> query = new QueryWrapper<>();
        query.eq("is_deleted", false);
        List<Salary> list = salaryService.list(query);
        return R.ok(list);
    }

    @GetMapping("/test-student")
    public R testStudent(@RequestParam Integer studentId) {
        Page<SalaryDTO> page = new Page<>(1, 10);
        Page<SalaryDTO> result = salaryService.getStudentSalaryPage(page, studentId);
        return R.ok(result);
    }

    
    @GetMapping("/test-join")
    public R testJoin() {
        // 直接调用mapper的关联查询方法
        Page<SalaryDTO> page = new Page<>(1, 10);
        Page<SalaryDTO> result = salaryService.getSalaryPage(page, null, null, null, null);
        return R.ok(result);
    }

   
    @PostMapping("/audit")
    public R audit(@RequestParam Integer id,
                   @RequestParam Integer status) {
        boolean success = salaryService.auditSalary(id, status);
        return success ? R.ok(null) : R.error("审核失败");
    }

 
    @PostMapping("/batch-audit")
    public R batchAudit(@RequestParam String ids,
                        @RequestParam Integer status) {
        String[] idArray = ids.split(",");
        boolean allSuccess = true;

        for (String idStr : idArray) {
            try {
                Integer id = Integer.parseInt(idStr.trim());
                boolean success = salaryService.auditSalary(id, status);
                if (!success) {
                    allSuccess = false;
                }
            } catch (NumberFormatException e) {
                allSuccess = false;
            }
        }

        return allSuccess ? R.ok(null) : R.error("部分审核失败");
    }


    @GetMapping("/student-page")
    public R studentSalaryPage(@RequestHeader("Authorization") String authHeader,
                               @RequestParam(defaultValue = "1") Integer page,
                               @RequestParam(defaultValue = "10") Integer size) {
        System.out.println("=== studentSalaryPage called ===");
        System.out.println("authHeader: " + authHeader);
        System.out.println("page: " + page);
        System.out.println("size: " + size);
        
        if (authHeader == null || authHeader.isEmpty()) {
            return R.error("未登录");
        }
        String token = authHeader.startsWith("Bearer ") ? authHeader.substring(7) : authHeader;
        Integer userId;
        try {
            userId = (Integer) JwtUtil.parseToken(token).get("userId");
            System.out.println("userId: " + userId);
        } catch (Exception e) {
            System.out.println("Token parse error: " + e.getMessage());
            return R.error("token无效");
        }
        // 查studentId
        var student = studentService.getByUserId(userId);
        if (student == null) {
            System.out.println("Student not found for userId: " + userId);
            return R.error("学生信息不存在");
        }
        Integer studentId = student.getId();
        System.out.println("studentId: " + studentId);

        // 使用studentId查询该学生的工资信息
        Page<SalaryDTO> pageObj = salaryService.getStudentSalaryPage(
                new Page<>(page, size), studentId
        );
        System.out.println("Query result: " + pageObj);
        return R.ok(pageObj);
    }
}